package com.ht.module.bus.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ht.abnormal.HtException;
import com.ht.constant.ErrorConstant;
import com.ht.module.bus.entity.BusRoom;
import com.ht.module.bus.entity.BusRoomUser;
import com.ht.module.bus.mapper.BusRoomUserMapper;
import com.ht.module.bus.service.BusRoomService;
import com.ht.module.bus.service.BusRoomUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.module.sys.mapper.SysUserMapper;
import com.ht.module.bus.vo.ShowUserVo;
import com.ht.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 房间用户表 服务实现类
 * </p>
 *
 * @author hejialun
 * @since 2024-11-25
 */
@Service
public class BusRoomUserServiceImpl extends ServiceImpl<BusRoomUserMapper, BusRoomUser> implements BusRoomUserService {
    @Resource
    private BusRoomService busRoomService;

    @Override
    public List<ShowUserVo> findRoomUserByRoomId(Integer roomId) {
        List<BusRoomUser> roomUsers = baseMapper.selectList(
                new QueryWrapper<BusRoomUser>()
                        .eq("room_id", roomId)
        );
        if (roomUsers.isEmpty()) {
            return new ArrayList<>();
        }
        return baseMapper.findRoomUserByRoomId(roomId);
    }

    @Override
    public BusRoom findLoginUserLatelyOpenRoom() {
        String userId = UserUtil.getUserId();
        if (StrUtil.isEmpty(userId)) {
            throw new HtException(ErrorConstant.PLEASE_LOGIN);
        }
        //优先查询出用户最近
        List<BusRoomUser> roomUsers = baseMapper.selectList(
                new QueryWrapper<BusRoomUser>()
                        .eq("user_id", userId)
                        .orderByDesc("create_date")
        );
        if (roomUsers.isEmpty()) {
            return null;
        } else {
            //获取房间id
            Integer roomId = roomUsers.get(0).getRoomId();
            //查询出当前房间
            BusRoom room = busRoomService.findById(roomId);
            //判断房间是否已经结束
            if (room.getIsStart() == 2) {
                //已经返回null
                return null;
            }
            return room;
        }


    }
}
